<template>
    <div class="common-layout">
        <el-row class="search-box">
            <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
                <el-form-item label="客户名称" prop="nickname">
                    <el-input v-model="queryParams.customerName" placeholder="请输入名称" clearable />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="Search" size="small" @click="queryList">搜索</el-button>
                </el-form-item>
            </el-form>
            <el-button type="primary" size="small" @click="toggleContent('content1')"
                :class="{ active: showContent === 'content1' }">
                护理记录
            </el-button>
            <el-button type="primary" size="small" @click="toggleContent('content2')"
                :class="{ active: showContent === 'content2' }">
                今日护理安排
            </el-button>
        </el-row>
        <el-container>
            <el-aside class="customerInfo">
                <div class="title">
                </div>
                <el-row v-loading="loading">
                    <el-table :data="tableData" size="big" @row-click="rowClick">
                        <el-table-column prop="indexId" label="序号" type="index" width="60" align="center" />
                        <!-- <el-table-column prop="id" label="用户编号" align="center" /> -->
                        <el-table-column prop="customerName" label="客户姓名" width="80px" align="center" />
                        <el-table-column prop="customerAge" label="年龄" width="60px" align="center" />
                        <el-table-column prop="customerSex" label="性别" width="60px" align="center"
                            :formatter="formatSex" />
                        <el-table-column prop="roomNo" label="房间号" width="70px" align="center" />
                        <el-table-column prop="bedId" label="床位号" width="70px" align="center" />
                        <el-table-column prop="levelName" label="护理级别" width="80px" align="center" />
                        <el-table-column prop="nickName" label="护理人员" width="80px" align="center" />
                    </el-table>

                    <el-pagination layout="sizes ,prev, pager, next, jumper, ->, total," :total="queryParams.total"
                        v-model:page-size="queryParams.size" v-model:current-page="queryParams.current"
                        @current-change="queryList" @size-change="queryList" :page-sizes="[2, 3, 5, 10, 20]" />
                </el-row>
            </el-aside>

            <el-aside class="outward">
                <div class="title">

                </div>
                <el-row v-loading="loading">
                    <div v-if="showContent === 'content1'">
                        <el-table :data="tableData1" size="big">
                            <el-table-column prop="indexId" label="序号" type="index" width="60" align="center" />
                            <!-- <el-table-column prop="id" label="用户编号" align="center" /> -->
                            <el-table-column prop="customerName" label="客户姓名" width="80px" align="center" />
                            <el-table-column prop="nursingName" label="项目名称" width="80px" align="center" />
                            <el-table-column prop="nursingTime" label="护理时间" width="110px" align="center" />
                            <el-table-column prop="nursingContent" label="护理内容" width="80px" align="center" />
                            <el-table-column prop="nursingCount" label="护理数量" width="80px" align="center" />
                            <el-table-column prop="nickName" label="护理人员" width="80px" align="center" />
                            <el-table-column label="操作" width="120px" align="center">
                                <template #default="scope">
                                    <el-button type="primary" size="small" icon="Edit" round
                                        @click="updateEdit(scope.row.id)">修改项目</el-button>
                                    <el-button type="danger" size="small" icon="Delete" round
                                        @click="deleteRecord(scope.row.id)">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>

                        <el-pagination layout="sizes ,prev, pager, next, jumper, ->, total," :total="queryParams1.total"
                            v-model:page-size="queryParams1.size" v-model:current-page="queryParams1.current"
                            @current-change="queryList" @size-change="queryList" :page-sizes="[2, 3, 5, 10, 20]" />
                    </div>
                    <div v-else-if="showContent === 'content2'">
                        <el-table :data="tableData2" size="big" :row-class-name="setRowClassName">
                            <el-table-column prop="indexId" label="序号" type="index" width="60" align="center" />
                            <!-- <el-table-column prop="id" label="用户编号" align="center" /> -->
                            <el-table-column prop="customerName" label="客户姓名" width="80px" align="center" />
                            <el-table-column prop="levelName" label="护理等级" width="80px" align="center" />
                            <el-table-column prop="nursingName" label="项目名称" width="80px" align="center" />
                            <el-table-column prop="nursingTime" label="护理时间" width="200px" align="center">
                                <template #default="scope">
                                    <div class="block">
                                        <el-date-picker v-model="scope.row.nursingTime" type="datetime"
                                            placeholder="" />
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column prop="nursingContent" label="护理内容" width="150px" align="center">
                                <template #default="scope">
                                    <el-input v-model="scope.row.nursingContent" placeholder="请输入护理内容" size="small" />
                                </template>
                            </el-table-column>
                            <el-table-column prop="nurseNu  mber" label="护理数量" width="80px" align="center">
                                <template #default="scope">
                                    <el-input v-model="scope.row.nursingCount" placeholder="请输入护理数量" size="small" />
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="60px" align="center">
                                <template #default="scope">
                                    <el-button type="success" size="small" icon="Check" circle
                                        @click="doneRecord(scope.row)"></el-button>
                                </template>
                            </el-table-column>
                        </el-table>

                        <el-pagination layout="sizes ,prev, pager, next, jumper, ->, total," :total="queryParams1.total"
                            v-model:page-size="queryParams1.size" v-model:current-page="queryParams1.current"
                            @current-change="queryList" @size-change="queryList" :page-sizes="[2, 3, 5, 10, 20]" />
                    </div>
                </el-row>


            </el-aside>
        </el-container>
        <el-dialog v-model="showEdit" title="项目编辑" style="width: 600px;">
            <Edit v-if="showEdit" :closeEdit="closeEdit" :editId="editId" />
        </el-dialog>
    </div>
</template>

<script setup name="careRecord">
import { ref, reactive, onMounted } from "vue";
import { getCustomerListSelf, getRecordListSelf, deleteRecordById, getNersingItemSelf, doneNursing } from '@/api/CareManagement/careRecord/index'
import { listLevel } from "@/api/CareManagement/careLevel/index";
import { ElMessageBox, ElNotification } from 'element-plus';
import Edit from './edit.vue'
const loading = ref(false)
const customerId = ref(0)
const levelIdold = ref(0)
const setId = ref(0)
const tableData = ref([])
const tableData1 = ref([])
const tableData2 = ref([])
const nursingLevelNames = ref([]);
const queryParams = reactive({
    customerId: "", // 客户ID
    customerName: "", // 客户名称
    current: 1, // 当前页码
    size: 10, // 每页大小
    total: 0 // 总记录数
});
const queryParams1 = reactive({
    customerId: "", // 客户ID
    customerName: "", // 客户名称
    current: 1, // 当前页码
    size: 10, // 每页大小
    total: 0 // 总记录数
});
const queryParams2 = reactive({
    customerId: "", // 客户ID
    customerName: "", // 客户名称
    current: 1, // 当前页码
    size: 10, // 每页大小
    total: 0 // 总记录数
});
const form = reactive({
    customerId: "", // 客户ID
    customerName: "", // 客户名称
    levelId: "", // 级别ID
    levelName: "", // 级别名称
    itemId: "", // 护理项目id
    nursinTime: "", // 护理时间
    nursingContent: "", // 护理设置内容
    nursingCount: "", // 护理次数
    userId: "",
})
const showEdit = ref(false)
const closeEdit = (query) => {
    showEdit.value = false; // 修改：确保对话框关闭
    if (query) {
        queryList(); // 仅在需要时刷新列表
    }
}
const editId = ref(0);
const updateEdit = (id) => {
    editId.value = id;
    showEdit.value = true;
};
const setRowClassName = (row) => {
    return row.row.isCompleted ? 'completed-row' : '';
};
const formatSex = (row, column, cellValue) => {
    return cellValue === 0 ? '男' : cellValue === 1 ? '女' : '';
};
const formatDate = (date) => {
    if (!date) return "";
    // 确保输入值为 Date 对象
    if (!(date instanceof Date)) {
        date = new Date(date); // 尝试将字符串转换为 Date 对象
    }
    if (isNaN(date.getTime())) {
        console.error("Invalid date:", date);
        return ""; // 如果日期无效，返回空字符串
    }
    const padZero = (num) => String(num).padStart(2, "0");
    const year = date.getFullYear();
    const month = padZero(date.getMonth() + 1);
    const day = padZero(date.getDate());
    const hours = padZero(date.getHours());
    const minutes = padZero(date.getMinutes());
    const seconds = padZero(date.getSeconds());
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};
const rowClick = (row) => {
    queryParams.customerName = row.customerName; // 同步到左侧表格的查询参数
    queryParams1.customerName = row.customerName; // 同步到右侧表格的查询参数
    queryParams2.customerName = row.customerName;
    queryList(); // 刷新两侧表格数据
    queryParams.customerName = "";
};

const queryList = async () => {
    loading.value = true;
    queryParams1.customerName = queryParams.customerName;
    queryParams2.customerName = queryParams.customerName;
    try {
        const page = await getCustomerListSelf({
            customerId: queryParams.customerId,
            customerName: queryParams.customerName,
            current: queryParams.current,
            size: queryParams.size
        });
        const page1 = await getRecordListSelf({
            customerId: queryParams1.customerId,
            customerName: queryParams1.customerName,
            current: queryParams1.current,
            size: queryParams1.size
        });
        const page2 = await getNersingItemSelf({
            customerId: queryParams2.customerId,
            customerName: queryParams2.customerName,
            current: queryParams2.current,
            size: queryParams2.size
        });
        // 校验返回值是否有效
        if (page && Array.isArray(page.records)) {
            tableData.value = page.records;
            queryParams.total = page.total || 0;
        } else {
            console.warn("客户列表数据结构异常:", page);
            tableData.value = [];
            queryParams.total = 0;
        }

        if (page1 && Array.isArray(page1.records)) {
            tableData1.value = page1.records;
            queryParams1.total = page1.total || 0;
        } else {
            console.warn("记录列表数据结构异常:", page1);
            tableData1.value = [];
            queryParams1.total = 0;
        }
        if (page2 && Array.isArray(page2.records)) {
            // 设置护理数量默认值为1，护理时间默认值为当前时间
            tableData2.value = page2.records.map(item => {
                return {
                    ...item,
                    nursingCount: item.nursingCount || 1,
                    nursingTime: item.nursingTime || formatDate(new Date())
                };
            });
            queryParams2.total = page2.total || 0;
        } else {
            console.warn("项目列表数据结构异常:", page2);
            tableData2.value = [];
            queryParams2.total = 0;
        }
    } catch (e) {
        console.error("查询列表失败:", e);
    } finally {
        loading.value = false;
    }
};
const doneRecord = (row) => {
    console.log("row", row);
    row.nursingTime = formatDate(row.nursingTime);
    doneNursing(row).then(success => {
        ElNotification({
            title: '消息',
            type: 'success',
            message: "护理完成",
        });
        // queryList(); // 刷新列表
        // 本地标记该行为已完成，并触发视图更新
        const index = tableData2.value.findIndex(item => item.id === row.id);
        if (index > -1) {
            tableData2.value[index].isCompleted = true;
        }
    }).catch(error => {
        console.error("护理完成失败:", error);
        ElNotification({
            title: '错误',
            type: 'error',
            message: "护理完成失败",
        });
    });
};
const deleteRecord = (id) => {
    ElMessageBox.confirm(
        '是否确认删除该护理记录?',
        'Warning',
        {
            confirmButtonText: '删除',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            deleteRecordById(id).then(success => {
                ElNotification({
                    title: '消息',
                    type: 'success',
                    message: "删除成功",
                })
                queryList();
            })
        })

}
const showContent = ref('content1'); // 新增：控制显示内容的状态变量

const toggleContent = (content) => {
    showContent.value = content; // 切换显示内容
};

onMounted(() => {
    queryList()
    listLevel().then(res => { // 加载护理等级列表
        nursingLevelNames.value = res.data.map(item => item.levelName); // 获取护理等级名称列表
    })
})
</script>

<style scoped>
.input-with-select .el-input-group__prepend {
    background-color: var(--el-fill-color-blank);
}

.insertButton {
    margin: 0px 0px 10px 0px;
}

.divider {
    margin: 0px 0px 10px 0px;
}

.search-box {
    width: 100%;
    margin: 0px 0px 10px 0px;
}

/* 客户信息 */
.customerInfo {
    width: 600px;
    height: 650px;
    border: 1px solid rgb(0, 0, 0);
    margin-right: 10px;
    border-radius: 10px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    /* 添加阴影效果 */
}

.customerInfo .title {
    background-color: #61b3ff;
    font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
    text-align: center;
    /* 将文字居中 */
    margin: 0;
    /* 移除默认的外边距 */
    padding: 10px;
    /* 添加内边距 */
    color: #333;
    /* 深灰色文字 */
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    /* 添加阴影效果 */
}

/* 外出登记 */
.outward {
    margin: 0;
    width: 790px;
    height: 650px;
    border: 1px solid rgb(0, 0, 0);
    /* margin-right: 20px; */
    border-radius: 10px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    /* 添加阴影效果 */
}

.outward .title {
    background-color: #61b3ff;
    font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
    text-align: center;
    /* 将文字居中 */
    margin: 0;
    /* 移除默认的外边距 */
    padding: 10px;
    /* 添加内边距 */
    color: #333;
    /* 深灰色文字 */
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    /* 添加阴影效果 */
}

.completed-row {
    background-color: #f0f9eb !important;
    /* 浅绿色背景 */
}

/* 新增：激活状态下按钮的样式 */
.el-button.active {
    background-color: #2bff01;
    /* 可以根据需要调整颜色 */
    border-color: #7fff4d;
}
</style>